package apobates.gui.formatter.service;

import apobates.gui.formatter.reader.RemoteForm;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;

/**
 * 异步获取远程JSON内容
 * @author xiaofanku
 * @since 20230429
 */
public class RemoteJsonService extends Service<String>{
    private RemoteForm remoteForm;

    public RemoteForm getRemoteForm() {
        return remoteForm;
    }

    public void setRemoteForm(RemoteForm remoteForm) {
        this.remoteForm = remoteForm;
    }
    // cpu线
    private static int cpuThreads = Runtime.getRuntime().availableProcessors();
    @Override
    protected Task<String> createTask() {
        final int timeout = remoteForm.getTimeout()>0 && remoteForm.getTimeout()<800000?remoteForm.getTimeout():8000;
        return new Task<String>() {
            @Override
            protected String call() throws IOException, MalformedURLException {
                OkHttpClient.Builder builder = new OkHttpClient.Builder()
                        .readTimeout(timeout, TimeUnit.MILLISECONDS)
                        .writeTimeout(timeout, TimeUnit.MILLISECONDS)
                        .connectTimeout(timeout, TimeUnit.MILLISECONDS)
                        .callTimeout(timeout, TimeUnit.MILLISECONDS)
                        .connectionPool(new ConnectionPool(cpuThreads + 1, timeout, TimeUnit.MINUTES))
                        .retryOnConnectionFailure(true);
                if(remoteForm.getFilePath().startsWith("https")){
                    try {
                        X509TrustManager manager = SSLSocketClient.getX509TrustManager();
                        builder.sslSocketFactory(SSLSocketClient.getSocketFactory(manager), manager);
                        builder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                Request request = new Request.Builder()
                        .url(remoteForm.getFilePath())
                        .addHeader("Content-Type", "application/json; charset=UTF-8")
                        .build();

                try (Response response = builder.build().newCall(request).execute();
                     Reader reader = response.body().charStream();
                     BufferedReader bufferedReader = new BufferedReader(reader)) {
                    StringBuilder content = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        content.append(line);
                        content.append(System.lineSeparator());
                    }
                    return content.toString();
                }
            }
        };
    }
}
